package com.hwxm.ltim.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;

/**
 * 邮箱发送工具类
 */
@Slf4j
@Component
public class EmailUtil {

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String fromEmail;

    @Value("${spring.mail.nickname:LT-IM系统}")
    private String fromNickname;

    /**
     * 发送简单文本邮件
     */
    public void sendSimpleMail(String to, String subject, String content) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(fromEmail);
            message.setTo(to);
            message.setSubject(subject);
            message.setText(content);
            
            mailSender.send(message);
            log.info("简单邮件发送成功，收件人：{}", to);
        } catch (Exception e) {
            log.error("简单邮件发送失败，收件人：{}", to, e);
            throw new RuntimeException("邮件发送失败");
        }
    }

    /**
     * 发送HTML邮件
     */
    public void sendHtmlMail(String to, String subject, String content) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
            
            helper.setFrom(fromEmail, fromNickname);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            
            mailSender.send(message);
            log.info("HTML邮件发送成功，收件人：{}", to);
        } catch (MessagingException | UnsupportedEncodingException e) {
            log.error("HTML邮件发送失败，收件人：{}", to, e);
            throw new RuntimeException("邮件发送失败");
        }
    }

    /**
     * 发送验证码邮件
     */
    public void sendVerificationCode(String to, String code, Integer type) {
        String subject = getSubjectByType(type);
        String content = buildVerificationCodeContent(code, type);
        
        sendHtmlMail(to, subject, content);
    }

    /**
     * 根据验证码类型获取邮件主题
     */
    private String getSubjectByType(Integer type) {
        switch (type) {
            case 1:
                return "【LT-IM】注册验证码";
            case 2:
                return "【LT-IM】登录验证码";
            case 3:
                return "【LT-IM】密码重置验证码";
            case 4:
                return "【LT-IM】邮箱修改验证码";
            default:
                return "【LT-IM】验证码";
        }
    }

    /**
     * 构建验证码邮件内容
     */
    private String buildVerificationCodeContent(String code, Integer type) {
        String action = getActionByType(type);
        
        StringBuilder html = new StringBuilder();
        html.append("<!DOCTYPE html>");
        html.append("<html>");
        html.append("<head>");
        html.append("<meta charset=\"UTF-8\">");
        html.append("<title>验证码邮件</title>");
        html.append("<style>");
        html.append("body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }");
        html.append(".container { max-width: 600px; margin: 0 auto; padding: 20px; }");
        html.append(".header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 20px; text-align: center; border-radius: 10px 10px 0 0; }");
        html.append(".content { background: #f9f9f9; padding: 30px; border-radius: 0 0 10px 10px; }");
        html.append(".code-box { background: #fff; border: 2px dashed #667eea; padding: 20px; text-align: center; margin: 20px 0; border-radius: 8px; }");
        html.append(".code { font-size: 32px; font-weight: bold; color: #667eea; letter-spacing: 5px; }");
        html.append(".footer { text-align: center; margin-top: 30px; color: #666; font-size: 12px; }");
        html.append(".warning { background: #fff3cd; border: 1px solid #ffeaa7; padding: 15px; border-radius: 5px; margin: 20px 0; }");
        html.append("</style>");
        html.append("</head>");
        html.append("<body>");
        html.append("<div class=\"container\">");
        html.append("<div class=\"header\">");
        html.append("<h1>🚀 LT-IM 即时通讯系统</h1>");
        html.append("</div>");
        html.append("<div class=\"content\">");
        html.append("<h2>").append(action).append("</h2>");
        html.append("<p>您好！您正在进行").append(action).append("操作，请使用以下验证码完成验证：</p>");
        html.append("<div class=\"code-box\">");
        html.append("<div class=\"code\">").append(code).append("</div>");
        html.append("</div>");
        html.append("<div class=\"warning\">");
        html.append("<strong>⚠️ 安全提示：</strong><br>");
        html.append("• 验证码有效期为 5 分钟<br>");
        html.append("• 请勿将验证码泄露给他人<br>");
        html.append("• 如非本人操作，请忽略此邮件");
        html.append("</div>");
        html.append("<p>如果验证码无法使用，请重新获取或联系客服。</p>");
        html.append("</div>");
        html.append("<div class=\"footer\">");
        html.append("<p>此邮件由系统自动发送，请勿回复</p>");
        html.append("<p>© 2024 LT-IM 即时通讯系统</p>");
        html.append("</div>");
        html.append("</div>");
        html.append("</body>");
        html.append("</html>");
        
        return html.toString();
    }

    /**
     * 根据验证码类型获取操作描述
     */
    private String getActionByType(Integer type) {
        switch (type) {
            case 1:
                return "用户注册";
            case 2:
                return "用户登录";
            case 3:
                return "密码重置";
            case 4:
                return "邮箱修改";
            default:
                return "身份验证";
        }
    }
}
